<script type="text/javascript">
    $(document).ready(function() {
        $('#tblUsers tr').click(function() {
            $('#tblUsers tr').each(function() {
                if ($(this).hasClass('row_selected'))
                    $(this).toggleClass('row_selected');
            })
            $(this).toggleClass('row_selected');
        });

        $('.scroll-pane').jScrollPane();
        $('.scroll-pane-arrows').jScrollPane(
            {
                showArrows: true,
                horizontalGutter: 10
            }
        );
        $('.scroll-pane-arrows-big-grid').jScrollPane(
            {
                showArrows: true,
                horizontalGutter: 10
            }
        );

        function errorFormUser()
        {
            var error = '';
            var valor = '';
            
            valor = document.getElementById('firstname').value;
            if(valor == null || valor.length == 0 || /^\s+$/.test(valor))
                return "The First Name field is required";

            valor = document.getElementById('lastName').value;
            if(valor == null || valor.length == 0 || /^\s+$/.test(valor))
                return "The Last Name field is required";
            
            valor = document.getElementById('email').value;
            if(valor == null || valor.length == 0 || /^\s+$/.test(valor))
                return "The Email field is required";
            
            var filter = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/;
            if (!filter.test(valor))
                return "The Email field must contain a valid mail";
            
            valorId = document.getElementById('idUsuario').value;
            if(valorId == 0) {
                valor = document.getElementById('password').value;
                if(valor == null || valor.length < 5 || /^\s+$/.test(valor))
                    return "The Password field is required, must contain at least 5 characters";
                if(valor.length > 9)
                    return "The Password field can not contain more than 9 characters";
            }
            else {
                valor = document.getElementById('new_password').value;
                if(valor.length > 9)
                    return "The New Password field can not contain more than 9 characters";
                
                valor = valor.replace(/^\s+|\s+$/g, '');
                if(valor != '' && valor.length < 5)
                { return "The New Password field must contain at least 5 characters"; }
            }

            indice = document.getElementById("rol").selectedIndex;
            if(indice == null || indice == 0 ) {
              return "The Rol field is required";
            }

            return error;
        }

        $("#add_user").dialog(
            {
              autoOpen: false,
              modal: true,
              width: 'auto',
              heigth: 'auto',
              position: { my: "center top", at: "center top", of: window },
              buttons:{
                Save: function() {
                    var validationError = errorFormUser();
                    if(validationError == '') {
                        // Tengo que hacer una validación más, que corresponde a que
                        // el nombre del usuario (mail) no puede estar duplicado
                        var username = document.getElementById('email').value;
                        var idUser = document.getElementById('idUsuario').value;
                        $.ajax({
                             type: 'POST',
                             //Realizaremos la petición al metodo validUsername del controlador User
                             url: '<?php echo site_url(); ?>user/validUsernameJS',
                             dataType: 'text',
                             data:  "mail="+username+"&id="+idUser,
                             success: function(resp) {
                                if(resp == '1') add_form.submit();
                                else document.getElementById('user_form_msg').innerHTML = 'This User name (Email) already exists';
                             }
                         });
                    }
                    else {
                        document.getElementById('user_form_msg').innerHTML = validationError;
                    }
                },
                Close: function() {
                    $(this).dialog("close");
                },
              }
        });


        $("#email_everyone").dialog(
            {
              autoOpen: false,
              modal: true,
              width: 'auto',
              heigth: 'auto',
              buttons:{
                Send: function() {
                    valor = $("#message").val();
                    if(valor == null || valor.length < 15 || /^\s+$/.test(valor))
                        $('#mail_form_msg').text('The Message field is required, must contain at least 15 characters');
                    else mail_form.submit();
                },
                Close: function() {
                    $(this).dialog("close");
                },
              }
        });

    });

    function showUserModal($idUser)
    {
         $.ajax({
             type: 'POST',
             //Realizaremos la petición al metodo addUser del controlador User
             url: '<?php echo site_url(); ?>user/editUser/'+$idUser,
             
             //Cuando se procese con éxito la petición se ejecutará esta función
             success: function(resp) { 
                $('#add_user').dialog("open").html(resp);
                document.getElementById('user_form_msg').innerHTML = '* Required fields.';
             }
         });
    }

    function showEmailModal()
    {
        $('#mail_form_msg').text('* Required fields.');
        $('#email_everyone').dialog("open");
    }
</script>

<?php
if (count($usuarios) > 0) { ?>
<table width="80%">
	<tr>
    	<td class="menuActual">Config > Users</td>
    </tr>
    <tr>
    	<td align="center">
        	<table>
                <tr>
                	<td colspan="6">
                        <?php if(isset($result)) {
                            if($result === 'success') echo 'Message sent successfully';
                        } ?>
                        <div class="scroll-pane-arrows-big-grid"  style="height:400px;">
                            <table width="100%" id="tblUsers" class="tablaJerarquia">
                                <tr>    
                                    <td class="descripcion">First Name</td>
                                    <td class="descripcion">Last Name</td>
                                    <td class="descripcion">E-mail</td>
                                    <td class="descripcion">Rol</td>
                                    <td class="descripcion">Enabled</td>
                                    <td class="delete">Edit</td>   
                                </tr>                                
                                <tbody>
								<?php foreach($usuarios as $usuario) { ?>
                                <tr>
                                    <td class="tdDescripcion"><?php echo $usuario['firstName']; ?></td>
                                    <td class="tdDescripcion"><?php echo $usuario['lastName']; ?></td>
                                    <td class="tdDescripcion"><?php echo $usuario['email']; ?></td>
                                    <td class="tdDescripcion"><?php echo $usuario['rol']; ?></td>
                                    <td class="tdDescripcion"><?php echo $usuario['enabled']; ?></td>
                                    <td class="tdDescripcion">
                                    	<a href="#" onclick="showUserModal(<?=$usuario['id']?>)">Edit</a>
                                    </td>
                                </tr>
                                <?php } ?>                         
                                </tbody>
                            </table>
                        </div>
                    </td>
                </tr>
            </table>
        </td>
    </tr>
    <tr>
        <td class="footer">
            <input onclick="showUserModal(0)" value="Add User" type="button" class="footer_button" />
            <input onclick="showEmailModal()" value="E-mail Everyone" type="button" class="footer_button" />
        </td>            
    </tr>
</table>
<?php } else { echo 'No information'; }?>


<!-- FORMULARIOS POP-UP -->
<div class='modal-form' id="add_user"> 
</div>

<div class='modal-form' id="email_everyone">
    <?php 
    $attributes = array('id' => 'mail_form');
    echo form_open('user/sendMailEveryone', $attributes); ?>
    <table width="100%">
        <tr>
            <td class="menuActual">Config > Users > E-mail Everyone</td>
        </tr>
        <tr>
            <td>
                <span id='mail_form_msg' class="msg_error"></span>
                <table>
                    <tr>
                        <td class="descripcionForm"><?php echo form_label("Message: *", 'message'); ?></td>
                        <td class="descripcionForm"><?php 
                            $attributes = array('id' => 'message', 'rows' => '10','name' => 'message', 'cols' => '50',
                                                'value' => set_value('message'));
                            echo form_textarea($attributes); ?>
                        </td>
                    </tr>
                    <tr>
                        <td class="descripcionForm" colspan="2"><?php echo validation_errors(); ?></td>
                    </tr>
                </table>
            </td>
        </tr>
    </table>
    <?php echo form_close();?>
</div>